import api from '../../api'
import _ from 'lodash'

const storeConfig = {
  state: {
    cart: []
  },
  mutations: {
    AddToCart (state, product) {
      if (state.cart && state.cart.length) {
        const prod = _.find(state.cart, { id: product.id })

        if (prod) {
          prod.count += product.count
        } else {
          state.cart.unshift(product)
        }
      } else {
        state.cart.unshift(product)
      }
    },
    RemoveFromCart (state, productId) {
      const idx = _.findIndex(state.cart, { id: productId })
      state.cart.splice(idx, 1)
    },
    RemoveSomeFromCart (state, productIds) {
      productIds.forEach((productId) => {
        const idx = _.findIndex(state.cart, { id: productId })
        state.cart.splice(idx, 1)
      })
    },
    RefreshCart (state, cart) {
      state.cart = cart
    }
  },
  actions: {
    fetchCart ({ commit }) {
      return api.post('cart/query.action')
        .then(result => {
          commit('RefreshCart', result.cart)
        })
    },
    addToCart ({ commit }, product) {
      return api.post('cart/add.action', {
        data: product
      })
        .then(result => {
          if (result !== '') {
            commit('AddToCart', product)
          }
        })
    },
    removeFromCart ({ commit }, productId) {
      return api.post('cart/remove.action', {
        data: { id: productId }
      })
        .then(result => {
          if (result !== '') {
            commit('RemoveFromCart', productId)
          }
        })
    },
    removeSomeFromCart ({ commit }, productIds) {
      return api.post('cart/removeSome.action', {
        data: productIds
      })
        .then(result => {
          if (result !== '') {
            commit('RemoveSomeFromCart', productIds)
          }
        })
    }
  },
  getters: {
    cartTotal: (state) => {
      _.sumBy(state.cart, (product) => {
        if (product.price && product.count) {
          return product.price * product.count
        } else {
          return 0
        }
      })
    },
    cartCount: (state) => {
      return state.cart.length
    }
  }
}

export default storeConfig
